#pragma once

#include "../tcpServer.hpp"
#include <fstream>
#include <regex>
#include <sys/types.h>
#include <sys/stat.h>

std::unordered_map<int, std::string> status = {
    {100, "Continue"},
    {101, "Switching Protocol"},
    {102, "Processing"},
    {103, "Early Hints"},
    {200, "OK"},
    {201, "Created"},
    {202, "Accepted"},
    {203, "Non-Authoritative Information"},
    {204, "No Content"},
    {205, "Reset Content"},
    {206, "Partial Content"},
    {207, "Multi-Status"},
    {208, "Already Reported"},
    {226, "IM Used"},
    {300, "Multiple Choice"},
    {301, "Moved Permanently"},
    {302, "Found"},
    {303, "See Other"},
    {304, "Not Modified"},
    {305, "Use Proxy"},
    {306, "unused"},
    {307, "Temporary Redirect"},
    {308, "Permanent Redirect"},
    {400, "Bad Request"},
    {401, "Unauthorized"},
    {402, "Payment Required"},
    {403, "Forbidden"},
    {404, "Not Found"},
    {405, "Method Not Allowed"},
    {406, "Not Acceptable"},
    {407, "Proxy Authentication Required"},
    {408, "Request Timeout"},
    {409, "Conflict"},
    {410, "Gone"},
    {411, "Length Required"},
    {412, "Precondition Failed"},
    {413, "Payload Too Large"},
    {414, "URI Too Long"},
    {415, "Unsupported Media Type"},
    {416, "Range Not Satisfiable"},
    {417, "Expectation Failed"},
    {418, "I'm a teapot"},
    {421, "Misdirected Request"},
    {422, "Unprocessable Entity"},
    {423, "Locked"},
    {424, "Failed Dependency"},
    {425, "Too Early"},
    {426, "Upgrade Required"},
    {428, "Precondition Required"},
    {429, "Too Many Requests"},
    {431, "Request Header Fields Too Large"},
    {451, "Unavailable For Legal Reasons"},
    {501, "Not Implemented"},
    {502, "Bad Gateway"},
    {503, "Service Unavailable"},
    {504, "Gateway Timeout"},
    {505, "HTTP Version Not Supported"},
    {506, "Variant Also Negotiates"},
    {507, "Insufficient Storage"},
    {508, "Loop Detected"},
    {510, "Not Extended"},
    {511, "Network Authentication Required"}};

std::unordered_map<std::string, std::string> mimes = {
    {".aac", "audio/aac"},
    {".abw", "application/x-abiword"},
    {".arc", "application/x-freearc"},
    {".avi", "video/x-msvideo"},
    {".azw", "application/vnd.amazon.ebook"},
    {".bin", "application/octet-stream"},
    {".bmp", "image/bmp"},
    {".bz", "application/x-bzip"},
    {".bz2", "application/x-bzip2"},
    {".csh", "application/x-csh"},
    {".css", "text/css"},
    {".csv", "text/csv"},
    {".doc", "application/msword"},
    {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
    {".eot", "application/vnd.ms-fontobject"},
    {".epub", "application/epub+zip"},
    {".gif", "image/gif"},
    {".htm", "text/html"},
    {".html", "text/html"},
    {".ico", "image/vnd.microsoft.icon"},
    {".ics", "text/calendar"},
    {".jar", "application/java-archive"},
    {".jpeg", "image/jpeg"},
    {".jpg", "image/jpeg"},
    {".js", "text/javascript"},
    {".json", "application/json"},
    {".jsonld", "application/ld+json"},
    {".mid", "audio/midi"},
    {".midi", "audio/x-midi"},
    {".mjs", "text/javascript"},
    {".mp3", "audio/mpeg"},
    {".mpeg", "video/mpeg"},
    {".mpkg", "application/vnd.apple.installer+xml"},
    {".odp", "application/vnd.oasis.opendocument.presentation"},
    {".ods", "application/vnd.oasis.opendocument.spreadsheet"},
    {".odt", "application/vnd.oasis.opendocument.text"},
    {".oga", "audio/ogg"},
    {".ogv", "video/ogg"},
    {".ogx", "application/ogg"},
    {".otf", "font/otf"},
    {".png", "image/png"},
    {".pdf", "application/pdf"},
    {".ppt", "application/vnd.ms-powerpoint"},
    {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
    {".rar", "application/x-rar-compressed"},
    {".rtf", "application/rtf"},
    {".sh", "application/x-sh"},
    {".svg", "image/svg+xml"},
    {".swf", "application/x-shockwave-flash"},
    {".tar", "application/x-tar"},
    {".tif", "image/tiff"},
    {".tiff", "image/tiff"},
    {".ttf", "font/ttf"},
    {".txt", "text/plain"},
    {".vsd", "application/vnd.visio"},
    {".wav", "audio/wav"},
    {".weba", "audio/webm"},
    {".webm", "video/webm"},
    {".webp", "image/webp"},
    {".woff", "font/woff"},
    {".woff2", "font/woff2"},
    {".xhtml", "application/xhtml+xml"},
    {".xls", "application/vnd.ms-excel"},
    {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
    {".xml", "application/xml"},
    {".xul", "application/vnd.mozilla.xul+xml"},
    {".zip", "application/zip"},
    {".3gp", "video/3gpp"},
    {".3g2", "video/3gpp2"},
    {".7z", "application/x-7z-compressed"}};

class Util
{
private:
    static char hex2i(char c)
    {
        if (c >= '0' && c <= '9')
            return c - '0';
        else if (c >= 'a' && c <= 'f')
            return c - 'a' + 10;
        else if (c >= 'A' && c <= 'F')
            return c - 'A' + 10;
        else
            return -1;
    }

public:
    static size_t split(const std::string& src, const std::string& sep, std::vector<std::string>& subs)
    {
        size_t pos = 0;
        while (pos < src.size())
        {
            size_t found = src.find(sep, pos);
            if (found == std::string::npos)
            {
                subs.push_back(src.substr(pos));
                break;
            }
            if (found > pos)
                subs.push_back(src.substr(pos, found - pos));
            pos = found + sep.size();
        }
        return subs.size();
    }

    static bool readFile(const std::string& filename, std::string& buf)
    {
        std::ifstream ifs(filename, std::ios::binary);
        if (!ifs.is_open())
        {
            LOG(ERR, "open %s file failed", filename.c_str());
            exit(-1);
        }
        ifs.seekg(0, ifs.end);
        int fsize = ifs.tellg();
        ifs.seekg(0, ifs.beg);
        buf.resize(fsize);
        ifs.read(&buf[0], fsize);
        if (!ifs.good())
        {
            LOG(ERR, "read %s file failed", filename.c_str());
            return false;
        }
        ifs.close();
        return true;
    }

    static bool writeFile(const std::string& filename, const std::string& buf)
    {
        std::ofstream ofs(filename, std::ios::binary | std::ios::trunc);
        if (!ofs.is_open())
        {
            LOG(ERR, "open %s file failed", filename.c_str());
            exit(-1);
        }
        ofs.write(buf.c_str(), buf.size());
        if (!ofs.good())
        {
            LOG(ERR, "write %s file failed", filename.c_str());
            return false;
        }
        ofs.close();
        return true;
    }

    //url特殊字符编码 避免url和查询字符串的特殊字符与http请求内容冲突产生歧义
    static std::string urlEncode(const std::string& url, bool space2plus)
    {
        std::string ret;
        for (auto c : url)
        {
            if (c == '.' || c == '-' || c == '_' || c == '~' || isalnum(c))
            {
                ret += c;
                continue;
            }
            if (c == ' ' && space2plus)
            {
                ret += '+';
                continue;
            }
            //将特殊字符c转换为%HH的形式
            char tmp[4] = {0};
            snprintf(tmp, 4, "%%%02X", c);
            ret += tmp;
        }
        return ret;
    }

    static std::string urlDecode(const std::string& code, bool plus2space)
    {
        std::string url;
        for (int i = 0; i < code.size(); i++)
        {
            if (code[i] == '+' && plus2space)
            {
                url += ' ';
                continue;
            }
            //将%HH的形式转换为特殊字符
            if (code[i] == '%' && i + 2 < code.size())
            {
                char c = (hex2i(code[i + 1]) << 4) + hex2i(code[i + 2]);//两位16进制数转为10进制
                url += c;
                i += 2;
                continue;
            }
            url += code[i];
        }
        return url;
    }

    static std::string statusDesc(int code)
    {
        auto it = status.find(code);
        if (it == status.end())
            return "unknown status code";
        else
            return it->second;
    }

    static std::string extMime(const std::string& filename)//content-type
    {
        
        int pos = filename.find_last_of('.');
        if (pos == std::string::npos)
            return "application/octet stream";
        std::string ext = filename.substr(pos);
        auto it = mimes.find(ext);
        if (it == mimes.end())
            return "application/octet stream";
        return it->second;
    }

    static bool isDirectory(const std::string& filename)
    {
        struct stat st;
        int n = stat(filename.c_str(), &st);
        if (n < 0)
        {
            LOG(ERR, "get file stat failed");
            return false;
        }
        return S_ISDIR(st.st_mode);
    }

    static bool isRegular(const std::string& filename)
    {
        struct stat st;
        int n = stat(filename.c_str(), &st);
        if (n < 0)
        {
            //LOG(DEG, "get file stat failed");
            return false;
        }
        return S_ISREG(st.st_mode);
    }

    static bool isValidPath(const std::string& path)
    {
        std::vector<std::string> subs;
        split(path, "/", subs);
        int level = 0;//相对根目录(服务器资源目录)记为第0层 在遍历过程中如果层数<0 跳出了相对根目录 则路径不合法
        for (auto& sub : subs)
        {
            if (sub == "..")
            {
                level--;
                if (level < 0)
                    return false;
                continue;
            }
            level++;
        }
        return true;
    }
};

class HttpRequest
{
public:
    std::string _method;
    std::string _path;
    std::string _version;
    std::string _body;
    std::unordered_map<std::string, std::string> _headers;//头部字段
    std::unordered_map<std::string, std::string> _params;//查询字符串
    std::smatch _matches;//利用regex从资源路径提取到的数据

public:
    HttpRequest()
    : _version("HTTP/1.1")
    {}

    void reset()
    {
        _method.clear();
        _path.clear();
        _version = "HTTP/1.1";
        _body.clear();
        _headers.clear();
        _params.clear();
        std::smatch mathes;
        _matches.swap(mathes);
    }

    void setHeader(const std::string& key, const std::string& val) { _headers.insert(std::make_pair(key, val)); }

    bool hasHeader(const std::string& key) { return _headers.find(key) != _headers.end(); }

    std::string getHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    }

    void setParam(const std::string& key, const std::string& val) { _params.insert(std::make_pair(key, val)); }

    bool hasParam(const std::string& key) { return _params.find(key) != _params.end(); }

    std::string getParam(const std::string& key)
    {
        auto it = _params.find(key);
        if (it == _params.end())
            return "";
        return it->second;
    }

    size_t getContentLength()
    {
        if (!hasHeader("Content-Length"))
            return -1;
        std::string clen = getHeader("Content-Length");
        return std::stol(clen);
    }

    bool isKeepAlive() { return hasHeader("Connection") && _headers["Connection"] == "keep-alive"; }
};

class HttpResponse
{
public:
    int _status;
    std::string _body;
    std::unordered_map<std::string, std::string> _headers;//头部字段
    bool _redirect;
    std::string _redirect_url;
public:
    HttpResponse()
    : _status(200),
      _redirect(false)
    {}

    HttpResponse(int status)
    : _status(status),
      _redirect(false)
    {}

    void reset()
    {
        _status = 200;
        _body.clear();
        _headers.clear();
        _redirect = false;
        _redirect_url.clear();
    }

    void setHeader(const std::string& key, const std::string& val) { _headers.insert(std::make_pair(key, val)); }

    bool hasHeader(const std::string& key) { return _headers.find(key) != _headers.end(); }

    std::string getHeader(const std::string& key)
    {
        auto it = _headers.find(key);
        if (it == _headers.end())
            return "";
        return it->second;
    }

    void setContent(const std::string& body, const std::string& type)
    {
        _body = body;
        setHeader("Content-Type", type);
        setHeader("Content-Length", std::to_string(_body.size()));
    }

    void setRedirect(const std::string& url, int status = 302)
    {
        _status = status;
        _redirect = true;
        _redirect_url = url;
    }

    bool isKeepAlive() { return hasHeader("Connection") && _headers["Connection"] == "keep-alive"; } 
};

enum RecvStatus
{
    RECV_ERR = 0,
    RECV_LINE,
    RECV_HEAD,
    RECV_BODY,
    RECV_OVER
};

#define MAX_LINE 8192

class HttpContext
{
private:
    int _resp_status;
    RecvStatus _recv_status;
    HttpRequest _request;
    
private:
    bool recvAndParseLine(Buffer* buf)
    {
        //LOG(DEG, "recv line");
        if (_recv_status != RECV_LINE)
            return false;
        //接收请求行
        std::string line = buf->getLine();
        if (line.size() == 0)
        {
            if (buf->getAbleReadSize() > MAX_LINE)
            {
                _resp_status = 414;//URI too long
                _recv_status = RECV_ERR;
                return false;
            }
            //没读到换行 且请求行的长度不超过MAX_LINE 等待下次读取 buf的reader指针也不会移动 下次读取时仍从该位置开始
            return true;
        }
        if (line.size() > MAX_LINE)//读到了换行 但请求行长度超过了MAX_LINE
        {
            _resp_status = 414;//URI too long
            _recv_status = RECV_ERR;
            return false;
        }
        //读到了换行 并且请求行长度不超过MAX_LINE 则对请求行进行解析

        //解析请求行
        std::regex reg("(GET|POST|HEAD|PUT|DELETE) ([^?]*)(?:\\?(.*))? (HTTP/1\\.[01])(?:\n|\r\n)", std::regex::icase);
        std::smatch matches;
        if (!std::regex_match(line, matches, reg))//请求行解析失败
        {
            _resp_status = 400;//BAD REQUEST
            _recv_status = RECV_ERR;
            return false;
        }
        _request._method = matches[1];
        std::transform(_request._method.begin(), _request._method.end(), _request._method.begin(), ::toupper);//请求方法转为大写
        _request._path = Util::urlDecode(matches[2], false);
        _request._version = matches[4];
        std::string query_str = matches[3];

        std::vector<std::string> subs;
        Util::split(query_str, "&", subs);
        for (auto& s : subs)
        {
            int pos = s.find("=");
            if (pos == std::string::npos)//找不到等号 查询字符串格式有误
            {
                _resp_status = 400;//BAD REQUEST
                _recv_status = RECV_ERR;
                return false;
            }
            std::string key = Util::urlDecode(s.substr(0, pos), true);//w3c规定 查询字符串的空格在编码时需要转为+字符 因此在解码时需要将+转空格
            std::string val = Util::urlDecode(s.substr(pos + 1), true);
            _request.setParam(key, val);
        }
        _recv_status = RECV_HEAD;
        return true;
    }

    bool recvAndParseHead(Buffer* buf)
    {
        //LOG(DEG, "head begin");
        if (_recv_status != RECV_HEAD)
            return false;
        while (true)
        {
            std::string line = buf->getLine();
            if (line.size() == 0)
            {
                if (buf->getAbleReadSize() > MAX_LINE)
                {
                    _resp_status = 414;//URI too long TODO:状态码是否需要修改
                    _recv_status = RECV_ERR;
                    LOG(DEG, "URL TOO LONG1");
                    return false;
                }
                //没读到换行 且请求行的长度不超过MAX_LINE 等待下次读取
                return true;
            }
            if (line.size() > MAX_LINE)//读到了换行 但请求行长度超过了MAX_LINE
            {
                _resp_status = 414;//URI TOO LONG
                _recv_status = RECV_ERR;
                LOG(DEG, "URL TOO LONG2");
                return false;
            }
            if (line == "\n" || line == "\r\n")//读取到空行 则头部字段全部读取完毕
                break;
            
            //解析当前读取到的头部字段
            if (line.back() == '\n') line.pop_back();
            if (line.back() == '\r') line.pop_back();
            int pos = line.find(": ");
            if (pos == std::string::npos)
            {
                _resp_status = 400;//BAD REQUEST
                _recv_status = RECV_ERR;
                LOG(DEG, "BAD REQUEST");
                return false;
            }
            std::string key = line.substr(0, pos);
            std::string val = line.substr(pos + 2);//:后面有一个空格 TODO:这里没有把每个头部字段的换行去掉
            _request.setHeader(key, val);
        }
        _recv_status = RECV_BODY;
        //LOG(DEG, "head end");
        return true;
    }


    bool recvBody(Buffer* buf)
    {
        //LOG(DEG, "recv body");
        if (_recv_status != RECV_BODY)
            return false;
        //获取实际完整的正文长度
        int content_length = _request.getContentLength();
        //LOG(DEG, "Content-Length: %d", content_length);
        if (content_length <= 0)//请求没有正文
        {
            _recv_status = RECV_OVER;
            return true;
        }
        //已经读取到的正文长度 _request.body.size()
       
        //还需要读取的正文长度
        int remain = content_length - _request._body.size();

        std::string s;
        if (buf->getAbleReadSize() >= remain)//缓冲区剩余长度满足还需要读取的长度 则正文内容成功完整读取
        {
            buf->ReadAsString(s, remain);
            _request._body += s;
            _recv_status = RECV_OVER;
            return true;
        }
        //缓冲区剩余长度不满足还需要读取的长度 则将缓冲区剩余长度读取后继续等待下一次读取
        buf->ReadAsString(s, buf->getAbleReadSize());
        _request._body += s;
        return true;
    }

public:
    HttpContext()
    : _resp_status(200),
      _recv_status(RECV_LINE)
    {}

    void reset()
    {
        _resp_status = 200;
        _recv_status = RECV_LINE;
        _request.reset();
    }

    int getRespStatus() { return _resp_status; }

    RecvStatus getRecvStatus() { return _recv_status; }

    HttpRequest getRequest() { return _request; }

    void RecvAndParse(Buffer* buf)
    {
        switch (_recv_status)
        {
        /*
        不用break 请求行接收解析之后直接对头部和正文进行处理
        如果某个环节处理失败 接收状态不会置为下一状态 那么后续的接口就不会往下处理
        */
        case RECV_LINE: recvAndParseLine(buf);
        case RECV_HEAD: recvAndParseHead(buf);
        case RECV_BODY: recvBody(buf); 
        }
    }
};

#define DEFAULT_TIMEOUT 10
#define DEFAULT_THREAD_COUNT 3

class HttpServer
{
using Handler = std::function<void(HttpRequest&, HttpResponse&)>;
using Handlers = std::vector<std::pair<std::regex, Handler>>;
private:
    Handlers _get_handlers;
    Handlers _post_handlers;
    Handlers _put_handlers;
    Handlers _delete_handlers;
    std::string _basedir;//静态资源根目录
    TcpServer _server;

private:
    bool isStaticHandler(HttpRequest& req)
    {
        if (_basedir.empty()) return false;
        if (req._method != "GET" && req._method != "HEAD") return false;
        if (!Util::isValidPath(req._path)) return false;
        std::string req_path = _basedir + req._path;//资源根目录+请求资源路径即为服务器资源的实际路径
        if (req._path.back() == '/')
            req_path += "index.html";//不直接在req._path上直接追加的原因是_path对应的文件不一定是常规文件也不一定存在 后续可能会进行功能性请求处理 不能直接修改路径
        if (!Util::isRegular(req_path)) return false;
        req._path = req_path;//到这里请求一定是静态资源请求 将_path设置为实际的资源路径
        return true;
    }

    void staticHandler(HttpRequest& req, HttpResponse& res)//处理静态资源性请求
    {
        std::string body;
        if (!Util::readFile(req._path, body))
        {
            res._status = 404;
            errorHandler(res);
            return;
        }
        res.setContent(body, Util::extMime(req._path));
    }

    void dynamicHandler(HttpRequest& req, HttpResponse& res, Handlers& handlers)//处理动态功能性请求
    {
        for (auto& handler : handlers)
        {
            const std::regex& reg = handler.first;
            Handler& func = handler.second;
            if (std::regex_match(req._path, req._matches, reg))
            {
                func(req, res);
                return;
            }
        }
        res._status = 404;
        errorHandler(res);
    }

    void errorHandler(HttpResponse& res)
    {
        //组织一个错误页面返回给客户端
        std::string body = "<html><head><meta charset='UTF-8'/></head><body><h1>" +
                           std::to_string(res._status) + " " + Util::statusDesc(res._status) + 
                           "</h1></body></html>";
        res.setContent(body, "text/html");
    }

    void route(HttpRequest& req, HttpResponse& res)
    {
        if (isStaticHandler(req))
        {
            staticHandler(req, res);
            return;
        }
        if (req._method == "GET" || req._method == "HEAD")
            dynamicHandler(req, res, _get_handlers);
        else if (req._method == "POST")
            dynamicHandler(req, res, _post_handlers);
        else if (req._method == "PUT")
            dynamicHandler(req, res, _put_handlers);
        else if (req._method == "DELETE")
            dynamicHandler(req, res, _delete_handlers);
        else
        {
            res._status = 405;//METHOD NOT ALLOWED
            errorHandler(res);
        }
    }

    void sendResponse(const ConnectionPtr& connection, HttpRequest& req, HttpResponse& res)
    {
        //完善响应头部字段
        if (req.isKeepAlive())
            res.setHeader("Connection", "keep-alive");
        else
            res.setHeader("Connection", "close");
        if (res._redirect)
            res.setHeader("Location", res._redirect_url);
        
        //响应序列化
        std::string res_str;
        res_str += req._version + " " + std::to_string(res._status) + " " + Util::statusDesc(res._status) + "\r\n";//响应行
        for (auto& header : res._headers)//响应头部
            res_str += header.first + ": " + header.second + "\r\n";
        res_str += "\r\n";
        res_str += res._body;//响应正文

        //发送响应
        connection->send(res_str.c_str(), res_str.size());//只是把数据放入发送缓冲区开启写事件监控 实际发送要等待下一轮写事件触发
    }

    void onConnected(const ConnectionPtr& connection)
    {
        connection->setContext(HttpContext());
        LOG(DEG, "establish a new connection, id:%d", connection->getConnectionId());
    }

    //读取缓冲区请求数据 确保数据完整后 将请求数据解析为HttpRequest结构 根据请求方法和资源路径调用相应的请求处理函数 形成HttpResponse结构并返回
    void onMessage(const ConnectionPtr& connection)
    {
        Buffer* buf = connection->getInBuffer();
        while (buf->getAbleReadSize() > 0)
        {
            //获取连接上下文
            HttpContext* context = connection->getContext()->get<HttpContext>();
            //解析缓冲区中的请求数据
            context->RecvAndParse(buf);
            HttpRequest req = context->getRequest();
            HttpResponse res(context->getRespStatus());
            //根据请求方法和资源路径获取并调用相应的请求处理函数
            //  判断当前请求是否接收成功
            if (context->getRecvStatus() == RECV_ERR)
            {
                errorHandler(res);
                sendResponse(connection, req, res);
                //请求解析失败后清空输入缓冲区 防止后续关闭连接时可能检查输入缓冲区有无数据继续处理 
                buf->moveReader(buf->getAbleReadSize());                                                                   
                connection->checkOutBuffer();
                return;
            }
            //  判断当前请求是否接收完整
            if (context->getRecvStatus() != RECV_OVER)
                return;//等待连接下一轮读事件触发后读取当前请求的剩余部分 根据上下文接收状态继续接收请求
            route(req, res);
            //处理形成响应后 将响应结构组织为某种指定格式(json串) 返回给客户端
            sendResponse(connection, req, res);
            //判断是否为长连接 决定是否对连接进行关闭
            //如果是长连接 则一次读事件可能读取多个请求 那么需要接着对后续的请求进行处理 直到缓冲区无内容(所有请求处理完毕)、请求不完整或请求解析失败时退出
            context->reset();//成功进行一次响应后 需要重置上下文的接收状态等信息 对下一条请求进行接收解析并处理
            if (!req.isKeepAlive())//短连接处理一次请求后 直接关闭连接
                connection->checkOutBuffer();//设置连接为半关闭状态 写事件触发 发送响应后直接关闭连接
        }
    }

public:
    HttpServer(uint16_t port)
    : _server(port)
    {
        _server.setThreadCount(DEFAULT_THREAD_COUNT);
        _server.enableInactiveRelease(DEFAULT_TIMEOUT);
        _server.setConnectedCallback(std::bind(&HttpServer::onConnected, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&HttpServer::onMessage, this, std::placeholders::_1));
    }

    void setBaseDir(const std::string& basedir) { _basedir = basedir; }

    void Get(const std::string& pattern, const Handler& handler) { _get_handlers.push_back(std::make_pair(std::regex(pattern), handler)); }

    void Post(const std::string& pattern, const Handler& handler) { _post_handlers.push_back(std::make_pair(std::regex(pattern), handler)); }

    void Put(const std::string& pattern, const Handler& handler) { _put_handlers.push_back(std::make_pair(std::regex(pattern), handler)); }

    void Delete(const std::string& pattern, const Handler& handler) { _delete_handlers.push_back(std::make_pair(std::regex(pattern), handler)); }

    void setThreadCount(int count) { _server.setThreadCount(count); }

    void enableInactiveRelease(int timeout) { _server.enableInactiveRelease(timeout); }

    void start() { _server.start(); }
};